/*******************************************************************************
 * @project: aohuaproject
 * @package: com.aohua.px
 * @file: ApproversAssignEventAction.java
 * @author: fionn
 * @created: 2015年11月11日
 * @purpose:
 * 
 * @version: 1.0
 * 
 * 
 * Copyright 2015 HAND All rights reserved.
 ******************************************************************************/
package com.aohua.px;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.agile.api.APIException;
import com.agile.api.ChangeConstants;
import com.agile.api.IAgileObject;
import com.agile.api.IAgileSession;
import com.agile.api.ICell;
import com.agile.api.IChange;
import com.agile.api.IDataObject;
import com.agile.api.IItem;
import com.agile.api.INode;
import com.agile.api.IRow;
import com.agile.api.IStatus;
import com.agile.api.ITable;
import com.agile.api.ITwoWayIterator;
import com.agile.api.IUser;
import com.agile.api.ItemConstants;
import com.agile.api.WorkflowConstants;
import com.agile.px.ActionResult;
import com.agile.px.EventActionResult;
import com.agile.px.IEventAction;
import com.agile.px.IEventInfo;
import com.agile.px.IWFChangeStatusEventInfo;
import com.aohua.excel.ETypeApprover;
import com.aohua.excel.PurcheseApproverService;
import com.aohua.excel.QualityApproverService;
import com.hand.agile.utils.CellUtils;
import com.hand.agile.utils.ChangeUtils;
import com.hand.config.A9ListConfig;
import com.hand.config.SystemConfigAdaptor;

/**
 * @author fionn
 *
 */
public class ApproversAssignEventAction implements IEventAction {

    private static Logger log = Logger.getLogger(ApproversAssignEventAction.class);
    private A9ListConfig config;
    
    /**
     * 
     */
    public ApproversAssignEventAction() {
        // TODO Auto-generated constructor stub
    }

    /* (non-Javadoc)
     * @see com.agile.px.IEventAction#doAction(com.agile.api.IAgileSession, com.agile.api.INode, com.agile.px.IEventInfo)
     */
    @Override
    public EventActionResult doAction(IAgileSession session, INode arg1,
            IEventInfo arg2) {
        EventActionResult result = null;
        try {
            session.disableAllWarnings();
            String[] path = {"配置文件","质量采购审核人"};
            config = SystemConfigAdaptor.getCaseConfig(session.getAdminInstance(), path);
            IWFChangeStatusEventInfo info = (IWFChangeStatusEventInfo)arg2;
            IChange change = (IChange)info.getDataObject();
            result = new EventActionResult(info, doAction(session, change));
        }catch(Exception e) {
            e.printStackTrace(System.out);
            result = new EventActionResult(arg2, new ActionResult(ActionResult.EXCEPTION, e));
        }finally {
            try {
                session.enableAllWarnings();
            } catch (APIException e) {
                e.printStackTrace(System.out);
            }
        }
        return result;
    }

    private ActionResult doAction(IAgileSession session, IChange change) throws APIException {
        IStatus status = change.getStatus();
        ActionResult result = new ActionResult(ActionResult.NORESULT, status.getName() + " 不是 质量/采购 节点.");
        List<IDataObject> reviewers = ChangeUtils.getReviewers(change, status, WorkflowConstants.USER_APPROVER);
        String groups = QualityApproverService.APPROVE_GROUP_NAME+PurcheseApproverService.APPROVE_GROUP_NAME;
        for(IDataObject reviewer : reviewers) {
            String name = reviewer.getName();
            if(!groups.contains(name)) continue;
            Map<String, ETypeApprover> approverMap = getApproversByGroupName(config.getValue(), name); 
            addTypeApprovers(session, change, approverMap);
            result = new ActionResult(ActionResult.STRING, "添加 " +name +" 成功.");
            break;
        }
        return result;
    }
    
    private void addTypeApprovers(IAgileSession session, IChange change, Map<String, ETypeApprover> approverMap) throws APIException {
        IStatus status = change.getStatus();
        Set<String> types = new HashSet<String>();
        // 受影响物件的类型(过滤重复的类型)
        ITable aitable = change.getTable(ChangeConstants.TABLE_AFFECTEDITEMS);
        ITwoWayIterator it = aitable.getReferentIterator();
        while(it.hasNext()) {
            IItem row = (IItem)it.next();
            ICell cell = row.getCell(ItemConstants.ATT_TITLE_BLOCK_ITEM_TYPE);
            types.add(CellUtils.getCellStringValue(cell));
        }
        // 受影响物件对应的审批人(过滤重复的用户)
        Set<String> userids = new HashSet<String>();
        for(String type : types) {
            ETypeApprover approver = approverMap.get(type);
            System.out.println(" >>>>>>>>> Item Type: " + type + "  --> " + approver);
            if(approver != null)       userids.addAll(approver.getApprovers());
        }
        // 根据配置获取用户作为审批者
        List<IUser> users = new ArrayList<IUser>();
        for(String userid : userids) {
            IAgileObject obj = session.getObject(IUser.OBJECT_TYPE, userid);
            System.out.println(userid + " >>> 获取用户  >>> " + obj);
            if(obj == null) continue;
            IUser user = (IUser)obj;
            users.add(user);
        }
        List<IDataObject> oldapprovers = ChangeUtils.getReviewers(change, status, WorkflowConstants.USER_APPROVER);
        List<IDataObject> acknowledgers = ChangeUtils.getReviewers(change, status, WorkflowConstants.USER_ACKNOWLEDGER);
        List<IDataObject> observers = ChangeUtils.getReviewers(change, status, WorkflowConstants.USER_OBSERVER);
        
        // 增加审核者
        List<IDataObject> approvers = new ArrayList<IDataObject>();
        approvers.addAll(users);
        approvers.removeAll(oldapprovers);
        change.addReviewers(status, approvers, observers, acknowledgers, false, "");
        // 删除原来多于的审核者
        oldapprovers.removeAll(users);
        change.removeReviewers(status, oldapprovers, Collections.EMPTY_LIST, Collections.EMPTY_LIST, "");
    }
    
    private Map<String, ETypeApprover> getApproversByGroupName(String excelpath, String groupName) {
        Map<String, ETypeApprover> map = new HashMap<String, ETypeApprover>();
        List<ETypeApprover> approvers = null;
        if(QualityApproverService.APPROVE_GROUP_NAME.equals(groupName)) {
            QualityApproverService service = new QualityApproverService();
            approvers = service.getApprovers(excelpath);
        }else if(PurcheseApproverService.APPROVE_GROUP_NAME.equals(groupName)) {
            PurcheseApproverService service = new PurcheseApproverService();
            approvers = service.getApprovers(excelpath);
        }else {
            return Collections.EMPTY_MAP;
        }
        for(ETypeApprover approver : approvers) {
            log.debug(approver.getType() + " ==> " + approver);
            map.put(approver.getType(), approver);
        }
        return map;
    }
    
    public static void main(String[] args) {
        ApproversAssignEventAction action = new ApproversAssignEventAction();
        String excelpath = "/home/fionn/Workspace/Support/上海澳华/03 项目实施/规格/classes_userid.xlsx";
        log.debug(QualityApproverService.APPROVE_GROUP_NAME);
        action.getApproversByGroupName(excelpath, QualityApproverService.APPROVE_GROUP_NAME);
        log.debug(PurcheseApproverService.APPROVE_GROUP_NAME);
        action.getApproversByGroupName(excelpath, PurcheseApproverService.APPROVE_GROUP_NAME);
    }
}
